package com.aimosheng.main.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aimosheng.common.mob.LoginData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aimosheng.common.CommonAppConfig;
import com.aimosheng.common.Constants;
import com.aimosheng.common.HtmlConfig;
import com.aimosheng.common.activity.AbsActivity;
import com.aimosheng.common.activity.WebViewActivity;
import com.aimosheng.common.bean.UserBean;
import com.aimosheng.common.event.LoginSuccessEvent;
import com.aimosheng.common.http.HttpCallback;
import com.aimosheng.common.interfaces.CommonCallback;
import com.aimosheng.common.utils.SpUtil;
import com.aimosheng.common.utils.ToastUtil;
import com.aimosheng.common.utils.WordUtil;
import com.aimosheng.main.R;
import com.aimosheng.main.http.MainHttpConsts;
import com.aimosheng.main.http.MainHttpUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by cxf on 2018/9/17.
 * 手机登录
 */
public class LoginPhoneActivity extends AbsActivity {

    private static final int TOTAL = 60;
    private EditText mEditPhone;
    private EditText mEditCode;
    private TextView mBtnCode;
    private Handler mHandler;
    private int mCount = TOTAL;
    private HttpCallback mGetCodeCallback;
    private String mGetCodeAgain;
    private boolean mHasGetCode;
    private boolean mFirstLogin;//是否是第一次登录
    private boolean mIsShowRecommend;
    private TextView tv_phone_code;
    private String openId,nickName,avatar;
    private int type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login_phone;
    }

    @Override
    protected void main() {
        Intent intent = getIntent();
        if (intent.hasExtra("openId")) {
            openId = intent.getStringExtra("openId");
        }
        if (intent.hasExtra("nickName")) {
            nickName = intent.getStringExtra("nickName");
        }
        if (intent.hasExtra("avatar")) {
            avatar = intent.getStringExtra("avatar");
        }
        if (intent.hasExtra("type")) {
            type = intent.getIntExtra("type",0);
        }
        mGetCodeAgain = WordUtil.getString(R.string.login_get_code_again);
        mEditPhone = findViewById(R.id.edit_phone);
        mEditCode = findViewById(R.id.edit_code);
        mBtnCode = findViewById(R.id.btn_get_code);
        tv_phone_code = findViewById(R.id.tv_phone_code);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mCount--;
                if (mCount > 0) {
                    mBtnCode.setText(mCount + "s");
                    if (mHandler != null) {
                        mHandler.sendEmptyMessageDelayed(0, 1000);
                    }
                } else {
                    mBtnCode.setText(mGetCodeAgain);
                    mCount = TOTAL;
                    if (mBtnCode != null) {
                        mBtnCode.setEnabled(true);
                    }
                }
            }
        };

        MainHttpUtil.getLoginInfo(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    TextView loginTipTextView = findViewById(R.id.login_tip);
                    if (loginTipTextView != null) {
                        JSONObject loginInfo = obj.getJSONObject("login_alert");
                        String loginTip = loginInfo.getString("login_title");
                        SpannableString spannableString = new SpannableString(loginTip);
                        JSONArray msgArray = JSON.parseArray(loginInfo.getString("message"));
                        for (int i = 0, size = msgArray.size(); i < size; i++) {
                            final JSONObject msgItem = msgArray.getJSONObject(i);
                            String title = msgItem.getString("title");
                            int startIndex = loginTip.indexOf(title);
                            if (startIndex >= 0) {
                                ClickableSpan clickableSpan = new ClickableSpan() {

                                    @Override
                                    public void updateDrawState(TextPaint ds) {
                                        super.updateDrawState(ds);
                                        ds.setColor(0xff3399ee);
                                        ds.setUnderlineText(false);
                                    }

                                    @Override
                                    public void onClick(View widget) {
                                        WebViewActivity.forward(mContext, msgItem.getString("url"), false);
                                    }
                                };
                                int endIndex = startIndex + title.length();
                                spannableString.setSpan(clickableSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                        }
                        loginTipTextView.setText(spannableString);
                        loginTipTextView.setMovementMethod(LinkMovementMethod.getInstance());//不设置 没有点击事件
                        loginTipTextView.setHighlightColor(Color.TRANSPARENT); //设置点击后的颜色为透明
                    }
                }
            }
        });

        EventBus.getDefault().register(this);
    }


    public static void forward(Context context) {
        context.startActivity(new Intent(context, LoginPhoneActivity.class));
    }

    public static void forward(Context context, LoginData loginData) {
        Intent intent = new Intent(context, LoginPhoneActivity.class);
        intent.putExtra("openId",loginData.getOpenID());
        intent.putExtra("nickName",loginData.getNickName());
        intent.putExtra("avatar",loginData.getAvatar());
        intent.putExtra("type",loginData.getFlag());
        context.startActivity(intent);
    }

    public void phoneLoginClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_login) {
            login();
        } else if (i == R.id.btn_get_code) {
            getLoginCode();
        } else if (i == R.id.btn_tip) {
            forwardTip();
        } else if (i == R.id.ll_phone_code) {
            changePhoneCountryCode();
        }
    }

    /**
     * 选择手机号 国家区号
     */
    private void changePhoneCountryCode() {
        startActivityForResult(new Intent(mContext, ChoosePhoneCountryCodeActivity.class), ChoosePhoneCountryCodeActivity.INTENT_REQUEST_CODE);
    }

    private String mCountryCode = "86";//国家区号

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ChoosePhoneCountryCodeActivity.INTENT_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                if (tv_phone_code != null) {
                    mCountryCode = data.getStringExtra(Constants.INTENT_PHONE_COUNTRY_CODE);
                    tv_phone_code.setText(mCountryCode);
                }
            }
        }
    }

    /**
     * 手机号验证码登录
     */
    private void login() {
        String phoneNum = mEditPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtil.show(R.string.login_input_phone);
            mEditPhone.requestFocus();
            return;
        }
//        if (!ValidatePhoneUtil.validateMobileNumber(phoneNum)) {
//            mEditPhone.setError(WordUtil.getString(R.string.login_phone_error));
//            mEditPhone.requestFocus();
//            return;
//        }
        if (!mHasGetCode) {
            ToastUtil.show(R.string.login_get_code_please);
            return;
        }
        String code = mEditCode.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            ToastUtil.show(R.string.login_input_code);
            mEditCode.requestFocus();
            return;
        }
        if(!TextUtils.isEmpty(openId)){
            MainHttpUtil.login(phoneNum, code, mCountryCode,openId,nickName,avatar,type, new HttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String[] info) {
                    onLoginSuccess(code, msg, info);
                }
            });
        }else{
            MainHttpUtil.login(phoneNum, code, mCountryCode, new HttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String[] info) {
                    onLoginSuccess(code, msg, info);
                }
            });
        }
    }

    /**
     * 获取验证码
     */
    private void getLoginCode() {
        String phoneNum = mEditPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtil.show(R.string.login_input_phone);
            mEditPhone.requestFocus();
            return;
        }
//        if (!ValidatePhoneUtil.validateMobileNumber(phoneNum)) {
//            mEditPhone.setError(WordUtil.getString(R.string.login_phone_error));
//            mEditPhone.requestFocus();
//            return;
//        }
        mEditCode.requestFocus();
        if (mGetCodeCallback == null) {
            mGetCodeCallback = new HttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String[] info) {
                    if (code == 0) {
                        if (mBtnCode != null) {
                            mBtnCode.setEnabled(false);
                        }
                        if (mHandler != null) {
                            mHandler.sendEmptyMessage(0);
                        }
                        if (!TextUtils.isEmpty(msg) && msg.contains("123456")) {
                            ToastUtil.show(msg);
                        }
                    } else {
                        ToastUtil.show(msg);
                    }
                }
            };
        }
        mHasGetCode = true;
        MainHttpUtil.getLoginCode(phoneNum, tv_phone_code.getText().toString(), mGetCodeCallback);
    }


    /**
     * 登录即代表同意服务和隐私条款
     */
    private void forwardTip() {
        WebViewActivity.forward(mContext, HtmlConfig.LOGIN_PRIVCAY);
    }

    /**
     * 登录成功！
     */
    private void onLoginSuccess(int code, String msg, String[] info) {
        if (code == 0 && info.length > 0) {
            JSONObject obj = JSON.parseObject(info[0]);
            String uid = obj.getString("id");
            String token = obj.getString("token");
            mFirstLogin = obj.getIntValue("isreg") == 1;
            mIsShowRecommend = obj.getIntValue("issexrecommend") == 1;
            if (mIsShowRecommend) {
                CommonAppConfig.getInstance().setLoginInfo(uid, token, false);
            } else {
                CommonAppConfig.getInstance().setLoginInfo(uid, token, true);
            }
            SpUtil.getInstance().setStringValue(SpUtil.TX_IM_USER_SIGN, obj.getString("usersig"));
            //友盟统计登录
            getBaseUserInfo();
        } else {
            ToastUtil.show(msg);
        }
    }

    /**
     * 获取用户信息
     */
    private void getBaseUserInfo() {
        MainHttpUtil.getBaseInfo(new CommonCallback<UserBean>() {
            @Override
            public void callback(UserBean bean) {
                if (mIsShowRecommend) {
                    SetProfileActivity.forward(mContext, bean, true);
                } else {
                    MainActivity.forward(mContext, mFirstLogin, false);
                    EventBus.getDefault().post(new LoginSuccessEvent());
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccessEvent(LoginSuccessEvent e) {
        finish();
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        EventBus.getDefault().unregister(this);
        mHandler = null;
        MainHttpUtil.cancel(MainHttpConsts.GET_LOGIN_CODE);
        MainHttpUtil.cancel(MainHttpConsts.LOGIN);
        MainHttpUtil.cancel(MainHttpConsts.GET_BASE_INFO);
        MainHttpUtil.cancel(MainHttpConsts.GET_LOGIN_INFO);
        super.onDestroy();
    }
}
